/**
 * 
 */
package com.huniu.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

import com.huniu.analysis.dictionary.tree.manager.ITreeNodeManager;
import com.huniu.analysis.model.HtmlQuality;
import com.huniu.utility.constant.GlobalConstants;

/**
 * @author zandy (chenheng)
 * 
 */
public class SearchServiceImpl implements ISearchService {

	private ITreeNodeManager treeNodeManager;

	public void setTreeNodeManager(ITreeNodeManager treeNodeManager) {
		this.treeNodeManager = treeNodeManager;
	}

	public List<HtmlQuality> searchHtml(String keywords) {
		Set<String> keyWordsSet = treeNodeManager.findValuePairs(keywords);
		Iterator<String> iterator = keyWordsSet.iterator();
		List<HtmlQuality> globalList = new ArrayList<HtmlQuality>();
		while ( iterator.hasNext() ) {
			String keyWord = iterator.next();
			List<HtmlQuality> list = getCachedHtml(keyWord);
			globalList.addAll(list);
		}
		return globalList ;
	}

	@SuppressWarnings("unchecked")
	private List<HtmlQuality> getCachedHtml(String keyWords) {
		CacheManager singletonManager = CacheManager.create();
		Cache cache = singletonManager
				.getCache(GlobalConstants.HTML_QUALITY_CACHE_NAME);
		net.sf.ehcache.Element pair = cache.get(keyWords);
		List<HtmlQuality> htmlQualityList;
		if (pair != null) {
			htmlQualityList = (List<HtmlQuality>) pair.getValue();
		} else {
			htmlQualityList = new ArrayList<HtmlQuality>();
		}
		return htmlQualityList;
	}

}
